#!/usr/bin/env bash
# Presents FreeBSD "pkg search" results with additional information.
#
# Shows FreeBSD "pkg search" output with (a) if package is installed
# and (b) if different version is installed than the results.
#
# Example output:
#  $ bash search.sh xset
#  [*] xset-1.2.5                     User preference utility for X
#  [*] (installed: 1.1.1) xsetroot-1.1.2                 Root window parameter setting utility for X
#  [ ] xsettingsd-1.0.0.2_1           Daemon that implements the XSETTINGS specification

# Function to return modified "pkg search" results.
# Params:
#   $1: What to do "pkg search" for
function better_search_freebsd_package {
	# Get general search result
	local _search=$(pkg search "$1")
	# Get all installed package info
	local _installed=$(pkg info -a)

	local the_package=''
	local the_package_name=''
	local the_package_version=''
	local installed_package=''
	local installed_package_name=''
	local installed_package_version=''
	while IFS='' read line; do
		# Gather info from current line
		# Package name and version without description
		the_package="${line%% *}"
		# Package name only
		the_package_name="${the_package%-*}"
		# Package version only
		the_package_version="${the_package##*-}"

		# Gather info about installed package
		installed_package=$(grep "^${the_package_name}\-[0-9]" <<<"$_installed")
		installed_package="${installed_package%% *}"
		installed_package_name="${installed_package%%-*}"
		installed_package_version="${installed_package##*-}"

		# Print line
		if [ -z "$installed_package" ]; then
			echo -n '[ ] '
		else
			echo -n '[*] '
			if [ "$the_package_version" != "$installed_package_version" ]; then
				echo -n "(installed: ${installed_package_version}) "
			fi
		fi
		echo "$line"
	done <<<"$_search"
}

# When this script is run with an argument, pass it to the function.
better_search_freebsd_package "$1"

